package com.ibm.iisp.common.web.springmvc.converter;

import java.util.Collections;
import java.util.Set;

import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.ConditionalGenericConverter;

import com.ibm.iisp.common.vo.RefBean;

public class ArrayToRefBeanConverter implements ConditionalGenericConverter {

	@Override
	public Set<ConvertiblePair> getConvertibleTypes() {
		return Collections.singleton(new ConvertiblePair(Object[].class, RefBean.class));
	}

	@Override
	public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
		if (source != null) {
			Object[] src = (Object[]) source;
			if (src.length != 2) {
				throw new RuntimeException("数级长度只能为2,实际长度:" + src.length);
			}
			return new RefBean((String) src[0], (String) src[1]);
		}
		return null;
	}

	@Override
	public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
		return sourceType.isArray() && RefBean.class.isAssignableFrom(targetType.getType());
	}

}
